import { ref, reactive } from 'vue';
import { HttpResponse } from '@/plugins/axios';

export default function useMyPagination<T>(apiFunc: () => Promise<HttpResponse<T[]>>) {
  const loading = ref<boolean>(false);
  const pageNum = ref<number>(1);
  const pageSize = ref<number>(10);
  const total = ref<number>(0);

  interface Istate {
    tableData: T[];
    apiResult: T[];
  }
  const state: Istate = reactive({
    tableData: [],
    apiResult: [],
  });

  // 调用 api 获取 table 数据
  const initTableData = () => {
    loading.value = true;
    apiFunc()
      .then((res) => {
        loading.value = false;
        state.apiResult = res.result;
        total.value = res.result.length;
        state.tableData = handlePagination(res.result);
      })
      .catch((err: any) => err);
  };

  // 处理分页
  const handlePagination = (apiResult: typeof state.apiResult) => {
    return apiResult.filter((item: T, index: number) => {
      let idx = index - (pageNum.value - 1) * pageSize.value;
      return idx < pageSize.value && idx >= 0;
    });
  };

  // 表格当前页展示多少条
  const handleSizeChange = (val: number) => {
    pageSize.value = val;
    state.tableData = handlePagination(state.apiResult);
  };
  // 表格当前页
  const handleCurrentChange = (val: number) => {
    pageNum.value = val;
    state.tableData = handlePagination(state.apiResult);
  };

  return {
    loading,
    pageNum,
    pageSize,
    total,
    state,
    initTableData,
    handleSizeChange,
    handleCurrentChange,
  };
}
